<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ali;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\DiamondLog;
use app\common\model\game\Record;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\task\Lists;
use app\common\model\task\Userlog;
use app\common\model\user\Withdraw;
use fast\Date;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', "yanzheng"];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    public function refresh()
    {
        $this->success("", ['userinfo' => $this->auth->getUserinfo()]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $this->error("当前用户未注册");
//            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
//        $username = $this->request->post('username');
        $password = $this->request->post('password');
//        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $invite_code = $this->request->post('invite_code', "");
        if (!$mobile || !$password || !$code) {
            $this->error(__('Invalid parameters'));
        }
//        if ($email && !Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($mobile, $password, "", $mobile, ["invite_code" => $invite_code]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $province = $this->request->post('province');
        $city = $this->request->post('city');
        $area = $this->request->post('area');
        $gender = $this->request->post('gender');
        $profession = $this->request->post('profession');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
//        $bio = $this->request->post('bio');

        Db::startTrans();
        try {
            if ($gender) {
                $user->gender = $gender;
            }
            if ($profession) {
                $user->profession = $profession;
            }
            if ($username) {
                $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
                if ($exists) {
                    $this->error(__('Username already exists'));
                }
                $user->username = $username;
            }
            if ($nickname) {
                $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
                if ($exists) {
                    $this->error(__('Nickname already exists'));
                }
                $user->nickname = $nickname;
                $task = Userlog::where(['user_id' => $user->id, 'task_id' => 1])->find();
                if (!$task) {
                    Userlog::get_task(1, $user->id, 1, 1);
                }
            }
            if ($province) {
                $user->province = $province;
            }
            if ($city) {
                $user->city = $city;
            }
            if ($area) {
                $user->area = $area;
            }
            if (!empty($avatar)) {
                $user->avatar = $avatar;
                $task = Userlog::where(['user_id' => $user->id, 'task_id' => 2])->find();
                if (!$task) {
                    Userlog::get_task(2, $user->id, 1, 1);
                }
            }
            $user->save();
            //        $user->bio = $bio;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error("修改失败");
        }


        $this->success();
    }

    public function guide()
    {
        $user = $this->auth->getUser();
        if ($user->guide == 1) {
            $this->success();
        }
        Db::startTrans();
        try {
            Userlog::create([
                'user_id' => $user->id,
                'task_id' => 5,
                'status' => 1,
            ]);
            $user->is_guide = 1;
            $user->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success();
    }

    public function receive_guide()
    {
        $adta = Lists::user_list($this->auth->id);
        if ($adta['guide_status'] == 0 && $this->auth->is_guide_receive == 0) {//
            Db::startTrans();
            try {
                $user = $this->auth->getUser();
                $task = Lists::where('id', 5)->find();
                \app\common\model\scroll\Notify::log("{$task['name']},获得{$task['amount']}银币", $user->nickname, 1);//横幅

                //增加余额
                $before = $user->money;
                $after = function_exists('bcadd') ? bcadd($user->money, $task['amount'], 2) : $user->money + $task['amount'];
                MoneyLog::create([
                    'user_id' => $user->id, 'money' => $task['amount'],
                    'before' => $before, 'after' => $after,
                    'memo' => "引导任务奖励", 'type' => 8,
                    'createtime' => time()
                ]);
                $user->money = $after;
                $user->is_guide_receive = 1;//已领取引导任务奖励
                $user->save();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("");
        }
        $this->error("当前领取状态有误");
    }

    public function bind_account()
    {
//        $captcha = $this->request->post("captcha");
//        if (!$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
        $ali_account = $this->request->param("ali_account");
        $wx_account = $this->request->param("wx_account");
        if (!$ali_account || !$wx_account) {
            $this->error("请填写完整");
        }
        Db::startTrans();
        try {
            $user = $this->auth->getUser();

            $user->ali_account = $ali_account;
            $user->wx_account = $wx_account;
            $user->save();
            $task = Userlog::where(['user_id' => $this->auth->id, 'task_id' => 4])->find();
            if (!$task) {
                Userlog::get_task(4, $this->auth->id, 1, 1);
            }
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

//        $ret = Sms::check($this->auth->mobile, $captcha, 'bindaccount');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }

//        Sms::flush($this->auth->mobile, 'bindaccount');
        $this->success("", ['userinfo' => $this->auth->getUserinfo()]);
    }

    public function authentication()
    {
        $real_name = $this->request->post("real_name");
        $captcha = $this->request->post("captcha");
        $card_num = $this->request->post("card_num");

        $user = $this->auth->getUser();
        if ($user['real_status'] == 1) {
            $this->error("当前账号已实名");
        } else if ($user['real_status'] == 2) {
            $this->error("当前重新实名审核中");
        }

        if ($card_num) {
            $exists = \app\common\model\User::where('card_num', $card_num)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error("当前身份信息已存在");
            }
        }

        $ret = Sms::check($this->auth->mobile, $captcha, 'bindinfo');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        if ($user['real_status'] == 0) {
            $result = $this->yanzheng($card_num, $real_name);
            if ($result['respCode'] == "000") {
                $user->real_name = $real_name;
                $user->card_num = $card_num;
                $user->real_status = 1;
            } else {
                $msg = isset($result) ? $result['respMessage'] : "身份验证信息有误";
                $this->error($msg);
            }
        } else {
            $this->error("实名状态有误,请刷新后重试");
        }

        Sms::flush($this->auth->mobile, 'bindinfo');
        $user->save();
        $this->success("", ['userinfo' => $this->auth->getUserinfo()]);
    }

    public function yanzheng($idNo, $name)
    {
        $host = "https://idenauthen.market.alicloudapi.com";
        $path = "/idenAuthentication";
        $method = "POST";
        $appcode = "3e71106a601e4da38732bbbc27015138";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = "idNo={$idNo}&name={$name}";
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $result = curl_exec($curl);
        return json_decode($result, true);
    }

    public function apply_auth()
    {
        $user = $this->auth->getUser();
        if ($user->real_status != 1) {
            $this->error("当前实名未认证");
        }

        $user->real_status = 2;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function withdraw()
    {
        $price = $this->request->param("price");
        $type = $this->request->param("type", 0);
        $with_method = $this->request->param("with_method");

        if (!$with_method) {
            $this->error("请选择提现方式");
        }

        $user = $this->auth->getUser();
        $user_id = $this->auth->id;
        if ($this->auth->real_status == 0) {
            $this->error("请绑定真实账户后提现");
        }
        if ($with_method == 2) {
            $mobile = $user['wx_account'];
            $this->error("暂未开放");
            if (empty($this->auth->wx_account)) {
                $this->error("请绑定微信账户");
            }
        } elseif ($with_method == 1) {
            $mobile = $user['ali_account'];
            if (empty($this->auth->ali_account)) {
                $this->error("请绑定支付宝账户");
            }
        }
        $type_name = '';
        $model_log = null;
        switch ($type) {
            case 1:
                $type_name = 'gold';
                $model_log = new GoldLog();
                $bili = \app\common\model\Config::where('name', 'withdraw_gold')->value('value', 0);
                break;
            case 2:
                $model_log = new DiamondLog();
                $type_name = 'diamond';
                $bili = \app\common\model\Config::where('name', 'withdraw_diamonds')->value('value', 0);
                break;
            default:
                $this->error("当前提现方式有误");
                break;
        }

        $num = $price * $bili;
        if ($user[$type_name] < $num) {
            $this->error("当前金额不足");
        }

        if ($user['vip_type_id'] != 0) {
            $minimum_limit = \app\common\model\Config::where('name', 'minimum_limit')->value('value', 0);
            if ($price < $minimum_limit) {
                $this->error("小于VIP最低限额");
            }
        } else {
            $gold_lists = \app\common\model\Config::where('name', 'gold_lists')->value('value');
            $gold_list = explode(",", $gold_lists);
            if (!in_array($price, $gold_list)) {
                $this->error("当前提现金额有误");
            }
        }

        Db::startTrans();
        try {
            if ($user && $price != 0) {
                $before = $user[$type_name];
                $after = function_exists('bcadd') ? bcadd($user[$type_name], -$num, 2) : $user[$type_name] - $num;
                //更新会员信息
                $user->save([$type_name => $after]);
                //写入日志
                $log_id = $model_log->insertGetId([
                    'user_id' => $user_id, $type_name => -$num,
                    'before' => $before, 'after' => $after,
                    'memo' => "用户提现", 'type' => 2,
                    'createtime' => time()
                ]);

                Withdraw::create(['user_id' => $user_id, 'log_id' => $log_id, 'price' => $price, 'type' => $type, 'num' => $num, "with_method" => $with_method, 'with_sn' => isset($sn) ?? null,
                    'status' => isset($status) ?? 0]);
            }
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success();
    }

    /**
     * 立即签到
     */
    public function dosign()
    {
        $config = get_addon_config('signin');
        $signdata = $config['signinscore'];

        $lastdata = \addons\signin\model\Signin::where('user_id', $this->auth->id)->order('createtime', 'desc')->find();
        $successions = $lastdata && $lastdata['createtime'] > Date::unixtime('day', -1) ? $lastdata['successions'] : 0;
        $signin = \addons\signin\model\Signin::where('user_id', $this->auth->id)->whereTime('createtime', 'today')->find();
        if ($signin) {
            $this->error('今天已签到,请明天再来!');
        } else {
            $successions++;
            $score = isset($signdata['s' . $successions]) ? $signdata['s' . $successions] : $signdata['sn'];
            Db::startTrans();
            try {
                \addons\signin\model\Signin::create(['user_id' => $this->auth->id, 'successions' => $successions, 'createtime' => time()]);
                \app\common\model\User::score($score, $this->auth->id, "连续签到{$successions}天");
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error('签到失败,请稍后重试');
            }
            $this->success('签到成功!连续签到' . $successions . '天!获得' . $score . '积分');
        }
    }

    public function qrcode()
    {
        $params = [
            'text' => $this->request->domain() . "/h5/#/pages/login/register?invite_code=" . $this->auth->invite_code,
            'label' => '',
            'logo' => 0,
            'labelalignment' => 'center',
            'foreground' => '#000000',
            'background' => '#ffffff',
            'size' => 200,
            'padding' => 5,
            'logosize' => 10,
            'labelfontsize' => 10,
            'errorcorrection' => 'high'
        ];

        $qrcodePath = ROOT_PATH . 'public';
        $qr_url = '/uploads/qrcode/';
        $qr = $qr_url . $this->auth->id . ".png";
        if (!file_exists($qrcodePath . $qr)) {
            $qrCode = \addons\qrcode\library\Service::qrcode($params);
            $qrCode->writeFile($qrcodePath . $qr);
        }

        $this->success("", [
            'qrcode' => $qr
        ]);
    }

    public function apply_club()
    {
        $name = $this->request->param("club_name");
        $efficacious_num = \app\common\model\Config::where('name', 'efficacious_num')->value("value", 0);
        $month_earnings = \app\common\model\Config::where('name', 'month_earnings')->value("value", 0);

        $user_ids = \app\common\model\User::where('parent_id', $this->auth->id)->column('id');
        $user_num = Record::where(['user_id' => ['in', $user_ids]])->group('user_id')->count();//邀请参赛有效人数
        $earnings = DiamondLog::where(['user_id' => $this->auth->id])->where(['type' => ['in', [1, 3]]])->whereTime('createtime', '-30 days')->sum('diamond');//当月收益钻石

        if ($efficacious_num > $user_num || $month_earnings > $earnings) {
            $this->error("当前条件不符合");
        }

        if (!$name) {
            $this->error('请填写俱乐部名称');
        }
        $user = \app\common\model\User::get($this->auth->id);
        $user->is_club = 2;
        $user->club_name = $name;
        $user->save();
        $this->success();
    }
}
